package com.tc.itfarm.commons.interceptor;

import com.tc.itfarm.api.util.DateUtils;
import com.tc.itfarm.api.util.JsonMapper;
import com.tc.itfarm.model.Log;
import com.tc.itfarm.model.User;
import com.tc.itfarm.service.LogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * Created by wangdongdong on 2016/8/17.
 */
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
    @Resource
    private LogService logService;

    /**
     * 环绕方法 记录日志（包括失败）
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String name = joinPoint.getSignature().getName();
        // 传入的参数
        Object[] args = joinPoint.getArgs();
        Object arg = null;
        // 先执行方法
        Object result = joinPoint.proceed();
        if (args.length > 0) {
            arg = args[0];
        }
        // 新增、更新、删除时记录日志
        if ((!(arg instanceof Log)) && (name.startsWith("insert") || name.startsWith("update") || name.startsWith("delete"))) {
            saveLog(joinPoint, name, (Integer) result, arg);
        }
        return result;
    }

    /**
     * 保存日志
     * @param joinPoint
     * @param name
     * @param result
     * @param arg
     */
    private void saveLog(ProceedingJoinPoint joinPoint, String name, Integer result, Object arg) {
        Log log = new Log();
        log.setCreateTime(DateUtils.now());
        log.setModifyTime(DateUtils.now());
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        // 操作人
        log.setUserId(user.getRecordId());
        // 操作人姓名
        log.setUsername(user.getNickname());
        // 修改的对象内容
        String change = JsonMapper.toJson(arg);
        // 修改对象名称 判断是否成功
        String simpleName = (result > 0) ? arg.getClass().getSimpleName() : "失败";
        if (name.startsWith("insert")) {
            log.setType("新增" + simpleName);
            log.setNewContent(change);
        } else if (name.startsWith("update")) {
            log.setType("修改" + simpleName);
            log.setNewContent(change);
        } else if (name.startsWith("delete")) {
            log.setType("删除" + simpleName);
            log.setOldContent(change);
        }
        logService.insert(log);
    }

    public void doThrowing(JoinPoint joinPoint) {
        logger.error("----------------------------------------" + joinPoint.toString());
    }
}
